const couponModel = require('../model/couponModel.js')

async function add(ctx){
    let parentid = ctx.request.body.parentid
    let name = ctx.request.body.name
    let condition = ctx.request.body.condition
    let price = ctx.request.body.price
    let startTime = ctx.request.body.startTime
    let endTime = ctx.request.body.endTime
    
    if(!parentid){
        return ctx.body = {code:0,msg:'请选择优惠券分类',data:''}
    }
    if(!name){
        return ctx.body = {code:0,msg:'请输入优惠券名称',data:''}
    }
    if (!price){
        return ctx.body = {code:0,msg:'请输入优惠券金额',data:''}
    }
    if(!startTime){
        return ctx.body = {code:0,msg:'请选择开始时间',data:''}
    }
    if(!endTime){
        return ctx.body = {code:0,msg:'请选择结束时间',data:''}
    }
    if(parentid == 1 && !condition){
        return ctx.body = {code:0,msg:'请设置满减优惠条件',data:''}
    }
    if(startTime > endTime){
        return ctx.body = {code:0,msg:'xxx',data:''}
    }
    let date =  Date.now()
    if(endTime < date){
        return ctx.body = {code:0,msg:'yyy',data:''}
    }

    let res = await couponModel.add({parentid,name,condition,price,startTime,endTime})
    
    ctx.body = res


 
}

async function list(ctx){
    let id = parseInt(ctx.query.id)
    let page = parseInt(ctx.query.page) || 1
    let num = parseInt(ctx.query.num) ||100000
    let offset = (page -1 ) * num
    let res = await couponModel.list({id,offset,num})
    ctx.body = res
}

async function mod(ctx){
    let date = Date.now()
    let res = await couponModel.mod(date)
    ctx.body = res
}


async function get(ctx){
    let id = ctx.user.id
    let couponid = ctx.request.body.couponid
    let res = await couponModel.get({id,couponid})
    ctx.body = res
}

async function userlist(ctx){
    let uid = ctx.user.id
    let id = parseInt(ctx.query.id)
    if(id == 1 || id == 2 || id == 3 || id == 4){
        let res = await couponModel.userlist({uid,id})
        return ctx.body = res
    }
    return {code:0,msg:'参数错误',data:''}
}

async function del(ctx){
    let uid = ctx.user.id
    let id = ctx.query.id
    let res = await couponModel.del({uid,id})
    ctx.body = res 
}

module.exports = {add,list,mod,get,userlist,del}